const system = require('../../utils/system.js');
const examApi = require('../../utils/examApi.js');

Page({
  data: {
    loading: true,
    statusBarHeight: 0,
    navBarHeight: 44,
    questions: [],
    totalQuestions: 0,
    correctCount: 0,
    wrongCount: 0,
    examTitle: '',
    examId: '',
    mode: 'exam'
  },

  onLoad(options) {
    console.log('结果页面接收到的参数:', options);
    
    // 获取考试ID
    const examId = options.examId || '';
    const mode = options.mode || 'exam';
    
    this.setData({
      examId: examId,
      mode: mode,
      statusBarHeight: system.statusBarHeight,
      navBarHeight: system.navBarHeight || 44
    });
    
    // 加载考试结果
    this.loadExamResult();
  },

  async loadExamResult() {
    try {
      // 从本地存储获取考试结果
      const result = wx.getStorageSync('examResults_' + this.data.examId);
      
      if (!result) {
        throw new Error('未找到考试结果');
      }

      // 获取试卷详情
      const examPaper = await examApi.getExamPaperDetail(this.data.examId);
      
      // 获取试题列表
      const questions = await examApi.getExamQuestions(this.data.examId);
      
      // 合并答题结果和题目详情
      const questionDetails = questions.map(q => {
        const answer = result.answers.find(a => a.id === q.id);
        return {
          ...q,
          userAnswer: answer ? answer.userAnswer : '',
          isCorrect: answer ? answer.correct : false,
          options: JSON.parse(q.options || '{}')
        };
      });

      this.setData({
        examTitle: examPaper.title,
        questions: questionDetails,
        totalQuestions: questionDetails.length,
        correctCount: result.correctCount,
        wrongCount: result.wrongCount,
        loading: false
      });
    } catch (error) {
      console.error('加载考试结果失败:', error);
      wx.showToast({
        title: error.message || '加载失败',
        icon: 'none'
      });
      this.setData({ loading: false });
    }
  },

  // 返回上一页
  goBack() {
    wx.navigateBack({
      fail: () => {
        wx.redirectTo({
          url: '/pages/index/index'
        });
      }
    });
  },

  // 返回首页
  returnToHome() {
    wx.reLaunch({
      url: '/pages/index/index'
    });
  },

  // 再次尝试
  tryAgain() {
    wx.redirectTo({
      url: `/pages/question/index?examId=${this.data.examId}`
    });
  }
}); 